<?php

namespace app\services\activity\seckill;

use app\model\activity\seckill\StoreSeckillProduct;
use app\services\BaseServices;

class SeckillProductService extends BaseServices
{

    /**
     * Sync seckill products.
     *
     * @param int $seckillId
     * @param array $productsData
     * @return bool
     */
    public function syncSeckillProducts(int $seckillId, array $productsData): bool
    {
        try {
            // Start a transaction
            StoreSeckillProduct::startTrans();

            // First, delete existing seckill products
            StoreSeckillProduct::where('seckill_id', $seckillId)->delete();

            // Then, insert new seckill products
            $insertData = [];
            foreach ($productsData as $product) {
                $insertData[] = [
                    'seckill_id' => $seckillId,
                    'product_id' => $product['product_id'],
                    'product_attr_value_unique' => $product['product_attr_value_unique'] ?? '',
                    'activity_price' => $product['activity_price'],
                    'count' => $product['count'],
                    'sort' => $product['sort'] ?? 0,
                    'add_time' => time(),
                ];
            }

            // Insert batch data using the SeckillProduct model
            StoreSeckillProduct::insertAll($insertData);

            // Commit the transaction
            StoreSeckillProduct::commit();

            return true; // Successfully synced seckill products
        } catch (\Throwable $e) {

            // Rollback the transaction if an exception occurs
            StoreSeckillProduct::rollback();
            return false; // Return false for exception handling
        }
    }

}